#include "Main.h"


struct Shader{
int hashID;
GLuint Program;

//UNIFORMS
GLint MODELVIEW_MATRIX;
GLint PROJECTION_MATRIX;
GLint TEXTURE_0;
GLint MATERIAL;
GLint COLOR;



Shader(){hashID =0; Program =0;}
bool Load(string filename = "Data/Shaders/Basic"){
GLuint VertexHandle,FragmentHandle;
Program = glCreateProgram();
VertexHandle   = glCreateShader(GL_VERTEX_SHADER);
FragmentHandle = glCreateShader(GL_FRAGMENT_SHADER);
string VertCode,FragCode;
string FN =  BASEFILE + filename + ".vrt";

ifstream file(FN.c_str(),ifstream::in);
if(file.good() != true){MessageBoxA ( NULL, FN.c_str(), "Graphics Error", MB_OK );}
while(file.good()){VertCode += file.get();}
file.close(); VertCode.erase(VertCode.length()-1,1);

FN = BASEFILE + filename + ".frg";
file.open(FN.c_str(),ifstream::in);
while(file.good()){FragCode += file.get();}
file.close(); FragCode.erase(FragCode.length()-1,1);

const GLchar* vrtmp =static_cast<const GLchar*>(VertCode.c_str());
const GLchar* frtmp =static_cast<const GLchar*>(FragCode.c_str());
glShaderSource(VertexHandle,1,&vrtmp,NULL);
glShaderSource(FragmentHandle,1,&frtmp,NULL);

glCompileShader(VertexHandle);
glCompileShader(FragmentHandle);

GLint fr_CompileStatus, vr_CompileStatus, LinkStatus;

glGetShaderiv(VertexHandle,GL_COMPILE_STATUS,&vr_CompileStatus);
glGetShaderiv(FragmentHandle,GL_COMPILE_STATUS,&fr_CompileStatus);

if(vr_CompileStatus !=0 && fr_CompileStatus !=0){
glAttachShader(Program,VertexHandle);
glAttachShader(Program,FragmentHandle);

LinkStatus = 0;
glLinkProgram(Program);
glGetProgramiv(Program,GL_LINK_STATUS,&LinkStatus);
if(LinkStatus!= 0){

	MODELVIEW_MATRIX = glGetUniformLocation(Program,"modelview_matrix");
	PROJECTION_MATRIX = glGetUniformLocation(Program,"projection_matrix");
	TEXTURE_0 = glGetUniformLocation(Program,"texture0");
	COLOR = glGetUniformLocation(Program,"Color");
	MATERIAL = glGetUniformLocation(Program,"Material");

	glBindAttribLocation(Program,0,"a_Vertex");
	glBindAttribLocation(Program,1,"a_TexCoord");
	//glBindAttribLocation(Program,2,"a_Normal");
	

	return true;}
else{
	char err[300];
	glGetProgramInfoLog(Program,100,NULL,&err[0]);
	MessageBoxA ( NULL, err, "Shader Linker Error", MB_OK );return false; /*LINKER ERROR*/}
}
else{
	char err[849];
	glGetShaderInfoLog(FragmentHandle,849,NULL,&err[0]);
	MessageBoxA ( NULL, err, "Shader Compiler Error", MB_OK );return false;/*COMPILER ERROR*/}
}

void Use(){glUseProgram(Program);}

};